﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities;
using Business;
using DevComponents.DotNetBar;

namespace Presentation
{
    public partial class frmQuanLyTacGia : DevComponents.DotNetBar.Office2007Form
    {
        DataView dv = new DataView();
        DataTable dt;
        bool save;
        private bool isFormClosing = false;
        // Contant for the close message
        private const int WM_CLOSE = 16;
        //override the WndProc msg to trap the WM_CLOSE message
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_CLOSE)
                isFormClosing = true;
            base.WndProc(ref m);
        }
        public frmQuanLyTacGia()
        {
            InitializeComponent();
            dgvTacGia.AutoGenerateColumns = false;
        }

        private void frmQuanLyTacGia_Load(object sender, EventArgs e)
        {
            LoadGridView();
            save = false;

        }
        private void LoadGridView()
        {            
            dt = TacGiaService.GetTacGiaDataTable();
            dt.TableName = "TacGia";
            dt.AcceptChanges();
            dgvTacGia.DataSource = dt;
            dv.Table = dt;
            btnCapNhat.Enabled = true;
            
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtTimKiem_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsPunctuation(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtTimKiem_TextChanged(object sender, EventArgs e)
        {
            dv.RowFilter = "TenTacGia like '%" + txtTimKiem.Text + "%'";
            dgvTacGia.DataSource = dv;
            if (txtTimKiem.Text == "")
            {
                //dv.RowStateFilter = DataViewRowState.OriginalRows;
                dgvTacGia.DataSource = dt;
            }
        }

        private void dgvTacGia_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            int id = int.Parse(dgvTacGia["MaTacGia", e.Row.Index].Value.ToString());            
            if (!TacGiaService.CheckDelete(id))
            {
                MessageBoxEx.Show("Không thể xóa thể loại này!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
            if (id >= TacGiaService.GetCurrentID())
            {
                for (int i = e.Row.Index + 1; i < dgvTacGia.RowCount; i++)
                {
                    dgvTacGia["MaTacGia", i].Value = id;
                    id++;
                }

            }
        }

        private void dgvTacGia_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            int id = GetID();
            for (int i = e.Row.Index - 1; i < dgvTacGia.RowCount; i++)
            {
                dgvTacGia["MaTacGia", i].Value = id++;
            }
            
        }


        int GetID()
        {
            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            int id = -1;
            if (dtThem.Rows.Count == 0)
            {
                id = TacGiaService.GetCurrentID();
                if (id==1 && TacGiaService.GetTacGiaByMaTacGia(id) == null)
                    id = 0;
            }
            else
            {
                id = (int)dtThem.Rows[dtThem.Rows.Count - 1]["MaTacGia"];

            }
            return id + 1;
        }

        private bool CapNhat()
        {
            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
            DataTable dtCapNhat = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.Deleted;
            DataTable dtXoa = dv.ToTable();

            List<TacGiaDTO> listThem = new List<TacGiaDTO>();
            for (int i = 0; i < dtThem.Rows.Count; i++)
            {
                if (dtThem.Rows[i]["TenTacGia"].ToString() == "")
                    return false;
                TacGiaDTO tg = new TacGiaDTO();
                tg.MaTacGia = (int)dtThem.Rows[i]["MaTacGia"];
                tg.TenTacGia = (string)dtThem.Rows[i]["TenTacGia"];
                listThem.Add(tg);
            }

            List<int> listXoa = new List<int>();
            for (int i = 0; i < dtXoa.Rows.Count; i++)
            {
                int ma = (int)dtXoa.Rows[i]["MaTacGia"];
                listXoa.Add(ma);
            }

            List<TacGiaDTO> listCapNhat=new List<TacGiaDTO>();
            for (int i = 0; i < dtCapNhat.Rows.Count; i++)
            {
                if (dtCapNhat.Rows[i]["TenTacGia"].ToString() == "")
                    return false;
                TacGiaDTO tg = new TacGiaDTO();
                tg.MaTacGia = (int)dtCapNhat.Rows[i]["MaTacGia"];
                tg.TenTacGia = (string)dtCapNhat.Rows[i]["TenTacGia"];
                listCapNhat.Add(tg);
            }


            foreach (int maTacGia in listXoa)
            {
                TacGiaService.Delete(maTacGia);
            }

            foreach (TacGiaDTO tg in listCapNhat)
                TacGiaService.Update(tg);
            foreach (TacGiaDTO tg in listThem)
                TacGiaService.Insert(tg);
            
            save = false;
            dv.RowStateFilter = DataViewRowState.CurrentRows;
            btnCapNhat.Enabled = false;
            return true;
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
          
           if(CapNhat())
               MessageBoxEx.Show("Đã cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
               MessageBoxEx.Show("Không thể cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadGridView();
        }

        private void frmQuanLyTacGia_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (btnCapNhat.Enabled==true && save)
            {
                DialogResult r = MessageBoxEx.Show("Bạn có muốn lưu không?", "Thông báo!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (r == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    isFormClosing = false;
                }
                else if (r == DialogResult.Yes)
                {
                    if (!CapNhat())
                    {
                        e.Cancel = true;
                        isFormClosing = false;
                    }
                }
            }
        }

        private void dgvTacGia_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            save = true;
        }

        private void dgvTacGia_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (isFormClosing)
                return;
            if (e.RowIndex == dgvTacGia.RowCount - 1)
                return;
            if (e.FormattedValue.ToString() == "")
            {
                MessageBoxEx.Show("Không được bỏ trống!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Cancel = true;
                btnCapNhat.Enabled = false;
            }
        }
    }
}
